package controllers;

import java.util.ArrayList;
import java.util.List;

import models.Menu;
import models.Reply;
import models.ReplyKeyword;
import models.User;
import models.Weixin;
import models.WeixinProp;
import net.ufrog.common.utils.Strings;
import play.i18n.Messages;
import pojos.Keyword;
import utils.Page;
import utils.dict.Dicts;
import utils.json.Gsons;
import utils.json.serializer.PageSerializer;
import weixin.WXRequest;
import weixin.req.Button;
import weixin.resp.UserList;

import com.google.gson.reflect.TypeToken;

/**
 * 公众号控制器
 * 
 * @author ultrafrog
 * @version 1.0, 2014-11-06
 * @since 1.0
 */
public class Weixins extends Admin {

	/** 索引 */
	public static void index() {
		renderArgs.put("types", Dicts.elements(Weixin.Type.class).entrySet());
		render();
	}
	
	/** 获取当前公众号 */
	public static void current() {
		Weixin weixin = Weixin.current();
		if (weixin == null) weixin = new Weixin();
		renderJSON(weixin);
	}
	
	/**
	 * 保存公众号
	 * 
	 * @param id
	 * @param name
	 * @param originalCode
	 * @param code
	 * @param type
	 * @param appId
	 * @param appSecret
	 * @param aesKey
	 */
	public static void save(String id, String name, String originalCode, String code, String type, String appId, String appSecret, String aesKey) {
		// 初始化公众号
		Weixin weixin = Strings.empty(id) ? new Weixin() : Weixin.class.cast(Weixin.findById(id));
		
		// 设置属性并保存
		weixin.name = name;
		weixin.originalCode = originalCode;
		weixin.code = code;
		weixin.type = type;
		weixin.appId = appId;
		weixin.appSecret = appSecret;
		weixin.aesKey = aesKey;
		weixin.status = Strings.empty(weixin.status, Weixin.Status.CURRENT);
		weixin.save();
		Weixin.clearById(weixin.id);
		
		// 若添加公众号则默认加载所有关注列表
		if (Strings.empty(id)) {
			UserList ulist = null;
			while (true) {
				ulist = WXRequest.User.get(weixin, (ulist == null) ? null : ulist.nextOpenId);
				if (ulist.data == null || Strings.empty(ulist.nextOpenId)) break;
				for (String oid: ulist.data.openid) {
					User.saveByWeixin(weixin.id, oid);
				}
			}
		}
		
		// 返回结果
		renderJSON(weixin);
	}
	
	/** 欢迎语设置 */
	public static void welcome() {
		// 读取当前公众号
		Weixin weixin = Weixin.current();
		if (weixin == null) {
			flash.error(Messages.get("weixin.current.null"));
			index();
		}
		
		// 查询数据
		WeixinProp welcome = WeixinProp.find("byWeixinAndCode", weixin.id, WeixinProp.Code.WELCOME).first();
		if (welcome == null) {
			welcome = new WeixinProp();
			welcome.value = "{}";
		}
		
		// 渲染视图
		renderArgs.put("welcome", Gsons.fromJson(welcome.value, Reply.class));
		renderArgs.put("types", Dicts.elements(Reply.Type.class).entrySet());
		render();
	}
	
	/**
	 * 保存欢迎语
	 * 
	 * @param type
	 * @param value
	 */
	public static void welcome_save(String type, String value) {
		// 查询数据
		Weixin weixin = Weixin.current();
		WeixinProp wxprop = WeixinProp.find("byWeixinAndCode", weixin.id, WeixinProp.Code.WELCOME).first();
		
		// 设置并保存数据
		if (wxprop == null) {
			wxprop = new WeixinProp();
			wxprop.code = WeixinProp.Code.WELCOME;
			wxprop.weixin = weixin.id;
		}
		wxprop.value = Gsons.toJson(new Reply(null, value, type, null));
		wxprop.save();
	}
	
	/** 自动回复 */
	public static void reply() {
		// 读取当前公众号
		Weixin weixin = Weixin.current();
		if (weixin == null) {
			flash.error(Messages.get("weixin.current.null"));
			index();
		}
		renderArgs.put("types", Dicts.elements(Reply.Type.class));
		render();
	}

	/**
	 * 自动回复查询
	 * 
	 * @param page
	 * @param size
	 */
	public static void reply_search(Integer page, Integer size) {
		Page<Reply> replyp = new Page<Reply>(page, size);
		Weixin weixin = Weixin.current();
		List<Reply> replys = Reply.find("weixin = ? order by createTime desc", weixin.id).fetch(replyp.getPage(), replyp.getSize());
		
		for (Reply r: replys) {
			r.getKeywords();
		}
		
		replyp.setTotal(Reply.count("weixin = ?", weixin.id));
		replyp.getContent().addAll(replys);
		
		renderJSON(replyp, new PageSerializer());
	}
	
	/**
	 * 自动回复保存
	 * 
	 * @param id
	 * @param name
	 * @param keyword
	 * @param type
	 * @param value
	 */
	public static void reply_save(String id, String name, String keyword, String type, String value) {
		// 初始化
		Reply reply = null;
		List<Keyword> keywords = Gsons.fromJson(keyword, new TypeToken<List<Keyword>>(){}.getType());
		
		// 判断是否提交编号
		// 未提交编号添加数据
		// 否则更新数据
		if (Strings.empty(id)) {
			Weixin weixin = Weixin.current();
			reply = new Reply(name, value, type, weixin.id).save();
		} else {
			reply = Reply.findById(id);
			reply.name = name;
			reply.type = type;
			reply.value = value;
			reply.save();
			
			ReplyKeyword.delete("reply = ?", id);
		}
		
		// 遍历保存关键字
		reply.keywords = new ArrayList<ReplyKeyword>(keywords.size());
		if (keywords.size() == 0) {
			ReplyKeyword rk = new ReplyKeyword();
			rk.keyword = "default";
			rk.type = ReplyKeyword.Type.DEFAULT_MATCHING;
			rk.reply = reply.id;
			rk.save();
			
			reply.keywords.add(rk);
		} else {
			for (Keyword kw: keywords) {
				ReplyKeyword rk = new ReplyKeyword();
				
				rk.keyword = kw.name;
				rk.type = kw.checked ? ReplyKeyword.Type.PARTIAL_MATCHING : ReplyKeyword.Type.PERFECT_MATCHING;
				rk.reply = reply.id;
				rk.save();
				
				reply.keywords.add(rk);
			}
		}
		
		// 输出数据
		Reply.clear(reply.weixin);
		renderJSON(reply);
	}
	
	/**
	 * 自动回复删除
	 * 
	 * @param id
	 */
	public static void reply_delete(String id) {
		Reply reply = Reply.findById(id);
		if (reply != null) {
			ReplyKeyword.delete("reply = ?", id);
			reply.delete();
		}
	}

	/** 自定义菜单 */
	public static void menu() {
		Weixin weixin = Weixin.current();
		if (weixin == null) {
			flash.error(Messages.get("weixin.current.null"));
			index();
		}
		render();
	}
	
	/** 自定义菜单查询 */
	public static void menu_search() {
		Weixin weixin = Weixin.current();
		List<Menu> menus = Menu.find("weixin = ? and parent is null order by order", weixin.id).fetch();
		
		// 
		for (Menu menu: menus) {
			menu.getChildren();
		}
		renderJSON(menus);
	}
	
	/**
	 * 自定义菜单保存
	 * 
	 * @param id
	 * @param type
	 * @param name
	 * @param key
	 * @param url
	 * @param order
	 * @param parent
	 */
	public static void menu_save(String id, String type, String name, String key, String url, Integer order, String parent) {
		// 初始化
		Menu menu = null;
		
		// 判断并保存数据
		if (Strings.empty(id)) {
			Weixin weixin = Weixin.current();
			menu = new Menu(name, type, key, url, order, parent, weixin.id).save();
		} else {
			menu = Menu.findById(id);
			menu.name = name;
			menu.type = type;
			menu.key = key;
			menu.url = url;
			menu.order = order;
			menu.save();
		}
		
		// 输出数据
		menu.getChildren();
		renderJSON(menu);
	}
	
	/**
	 * 自定义菜单删除
	 * 
	 * @param id
	 */
	public static void menu_delete(String id) {
		Menu menu = Menu.findById(id);
		menu.delete();
	}
	
	/** 自定义菜单发布 */
	public static void menu_publish() {
		// 初始化
		Weixin weixin = Weixin.current();
		List<Menu> menus = Menu.find("weixin = ? and parent is null order by order", weixin.id).fetch();
		weixin.req.Menu menu = new weixin.req.Menu();
		
		// 生成对象
		for (Menu men: menus) {
			// 
			Button button = new Button();
			button.name = men.name;
			
			// 
			if (men.getChildren().size() > 0) {
				// 
				for (Menu m: men.getChildren()) {
					Button btn = new Button();
					btn.name = m.name;
					btn.type = m.type;
					btn.key = m.key;
					btn.url = m.url;
					button.subButton.add(btn);
				}
			} else {
				button.type = men.type;
				button.key = men.key;
				button.url = men.url;
			}
			menu.button.add(button);
		}
		
		// 发布信息
		WXRequest.Menu.create(weixin, menu);
	}
}
